from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

class Base():
    def __init__(self,driver):
        self.driver = driver

    def open_url(self,url):
        self.driver.get(url)

    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:driver.find_element(*loc))
            return self.driver.find_element(*loc)
        except Exception as w:
            print(w)

    def click(self,loc):
        self.find_element(loc).click()

    def text(self,loc):
        return self.find_element(loc).text

    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    # 滚动条（js注入）、
    def scrollTo(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    def scrollHeight(self):
        self.driver.execute_script(f'window.scrollTo(0,document.Height)')

    # alert弹窗处理、
    def alert_accept(self):
        self.driver.switch_to.alert().accept()

    def alert_dismiss(self):
        self.driver.switch_to.alert().dismiss()

    # iframe 切换、
    def iframe(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))

    def iframe_content(self):
        self.driver.switch_to.default_content()

    # 窗口切换、
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 鼠标事件、
    def double_click(self):
        ActionChains(self.driver).double_click().perform()

    def three_click(self):
        ActionChains(self.driver).double_click().click().perform()

    def context_click(self):
        ActionChains(self.driver).context_click().perform()

    def move_to_element(self,loc):
        ActionChains(self.driver).move_to_element(self.driver.find_element(loc)).perform()

    # 键盘事件、
    def jp_ENTER(self):
        self.find_element(Keys.ENTER)

    def jp_TAB(self):
        self.find_element(Keys.TAB)

    def jp_SPACE(self):
        self.find_element(Keys.SPACE)

    def jp_BACKSPACE(self):
        self.find_element(Keys.BACKSPACE)

    # 浏览器窗口操作、
    def back(self):
        self.driver.back()

    def close(self):
        self.driver.close()

    def refresh(self):
        self.driver.refresh()

    # 下拉框选择
    def index(self,loc,info):
        index = Select(self.driver.find_element(loc))
        index.select_by_index(info)

